;(function($){
	$.fn.pagination = function(opt){
		var settings = {
				totalPage:0, //总页数
				start:1, //开始页
				//url:'',
				refresh:'',//分页刷新				
				pageNum:6, //分页栏数量
				active:'am-active',
				disabled:'am-disabled'
			};
		settings = $.extend(settings, opt);	
		var me = $(this);	
		var pid = me.attr('id');
		me.addClass("am-cf");
		me.empty();
		me.append('<span>共'+settings.totalPage+'页</span>');
		me.append('<div class="am-fr"><ul id="pager_'+pid+'" class="am-pagination"></ul></div>');
		//coutine....		
		init(settings.start);
		
		function init(_start){
			var arr = [];					
			
			if(_start > 1){
				arr.push('<li><a href="javascript:void(0);">«</a></li>');
			}else{
				arr.push('<li class="am-disabled"><a href="javascript:void(0);">«</a></li>');
			}			
			var tps = settings.totalPage > (_start+settings.pageNum-1)?(_start+settings.pageNum-1):settings.totalPage;
			if(tps > 0){
				for(var i = _start; i <= tps; i++){
					if(i == _start){
						arr.push('<li id="page_'+i+'" class="am-active"><a href="javascript:void(0);">'+i+'</a></li>');
					}else{
						arr.push('<li id="page_'+i+'"><a href="javascript:void(0);">'+i+'</a></li>');
					}				
				}
			}
			if(settings.totalPage <= (_start+settings.pageNum-1)){
				arr.push('<li  class="am-disabled"><a href="javascript:void(0);">»</a></li>');
			}else{
				arr.push('<li><a href="javascript:void(0);">»</a></li>');
			}
			$("#pager_"+pid).empty();
			$("#pager_"+pid).append(arr.join(""));
			bulidEvent.call($("#pager_"+pid).find(">li>a"));
		}
		
		function bulidEvent(){
			$(this).bind({click: function(){
					onClick($(this));
				}				
			});
		}
		function onClick(li){
			var inx = li.text();
			if(inx == '«'){
				pre();
				return;
			}
			if(inx == '»'){
				next();
				return;
			}
			goPage(inx);
		}
		function goPage(inx){
			if(parseInt(inx) != me[0].p.currentPage){
				$("#pager_"+pid).find(">li").removeClass("am-active");
				$("#page_"+inx).addClass("am-active");
				me[0].p.currentPage = inx;
				if(typeof settings.refresh === 'function'){
					settings.refresh(parseInt(inx));
				}
			}			
		}
		function pre(){
			init(me[0].p.startPage - settings.pageNum);
			me[0].p.startPage -= settings.pageNum;			
			goPage(me[0].p.startPage);
		}
		function next(){
			init(me[0].p.startPage + settings.pageNum);
			me[0].p.startPage += settings.pageNum;
			goPage(me[0].p.startPage);
		}
		me.getCurrentPage = function(){
			return me[0].p.currentPage;
		}
		me[0].p = {currentPage:1, startPage:1};
		return me;
	};
})(jQuery);
